﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using DevExpress.Xpo;
using DevExpress.Data.Filtering;
using POI.eTransmittal.BusinessRule;
using POI.eTransmittal.Enitity;


namespace POI.eTransmittal.WebApp
{
    public partial class Main : BasePage 
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            xpodsOutstandingIncoming.Session = CurrentUnitOfWork;
            xpodsOutstandingIncoming.Criteria = CriteriaOperator.Parse("Status=? and CreatedBy=?", IncomingTransmittal.STATUS_DRAFT, this.CurrUserId).ToString();

            xpodsOutstandingOutgoing.Session = CurrentUnitOfWork;
            if(CurrentUserRole!=null){
                if(CurrentUserRole.AccessRights.Contains(AccessRights.MODIFY_OTHER_OUTGOING_TRANSMITTAL))
                    xpodsOutstandingOutgoing.Criteria = CriteriaOperator.Parse("Status=? or Status=?", OutgoingTransmittal.DRAFT, OutgoingTransmittal.WAIT).ToString();
                else
                    xpodsOutstandingOutgoing.Criteria = CriteriaOperator.Parse("Status=? and CreatedBy=?", OutgoingTransmittal.DRAFT, this.CurrUserId).ToString();
            }
           

            xpoDsContact.Session = CurrentUnitOfWork;
            xpodsDocType.Session = CurrentUnitOfWork;
            xpoDsInbox.Session = CurrentUnitOfWork;
            xpodsTransUser.Session = CurrentUnitOfWork;
            xpodsUser.Session = CurrentUnitOfWork;
            if(CurrentUserRole!=null)
            roundPanelIncoming.Visible = CurrentUserRole.AccessRights.Contains(AccessRights.MODIFY_OWNED_INCOMING_TRANSMITTAL);
        }

        private void DistributePop(string p)
        {
            SavePopUp(p, true);

        }

        private void SavePopUp(string logNo, bool isDistribute)
        {
            //   IncomingTransmittal trns = CommonBusinessRules.GetIncomingTransmittal(CurrentUnitOfWork, p);


            if (!string.IsNullOrEmpty(logNo))
            {

                int Log = Convert.ToInt32(logNo);
                int step = -1;
                bool isErr = false;
                string shareFolder = "";
                try
                {
                    string inbox = cboPopInbox.Text;
                    DateTime receivedDate = dtePopReceivedDate.Date;
                    string subject = txtPopSubject.Text;


                    string remarks = txtPopRemarks.Text;
                    string from = cboPopFrom.Text;

                    string attn = hfField.Contains("Attn") ? hfField["Attn"].ToString() : "";
                    string cc = hfField.Contains("Cc") ? hfField["Cc"].ToString() : ""; 
                    TempFile file = TempFile.GetFileFromSession(this);
                    step = 1;
                    if (file == null)
                    {

                        CommonBusinessRules.SaveIncoming(CurrentUnitOfWork, logNo, inbox, receivedDate, subject, from, attn, cc, CurrUserId, remarks);
                        if (isDistribute)
                        {
                            step = 3;
                            CommonBusinessRules.DistributeIncomingTransmittal(CurrentUnitOfWork, Log);
                        }

                    }
                    else
                    {

                        string ext = Path.GetExtension(file.File.FileName);

                        CommonBusinessRules.CheckExtention(CurrentUnitOfWork, ext);
                        string path = CommonBusinessRules.GetIncomingShareFolderToWrite(CurrentUnitOfWork);
                        step = 2;
                        string newFileName = CommonBusinessRules.GetIncomingTransmittalFileName(CurrentUnitOfWork, Log, Path.GetExtension(file.File.FileName));
                        shareFolder = Path.Combine(path, newFileName);
                        file.File.SaveAs(shareFolder);

                        CommonBusinessRules.SaveIncoming(CurrentUnitOfWork, logNo, inbox, receivedDate, subject, from, attn, cc, CurrUserId, remarks, shareFolder, file.File.FileName);
                        if (isDistribute)
                        {
                            step = 3;
                            CommonBusinessRules.DistributeIncomingTransmittal(CurrentUnitOfWork, Log, shareFolder, file.File.FileName);
                        }
                    }
                    //   string cc = .Text;

                }
                catch (Exception ex)
                {
                    isErr = true;
                    switch (step)
                    {
                        case 1:

                            SetErrorMessage("Unable to save data, please contact database administrator.;" + ex.Message, hfField);
                            break;
                        case 2:
                            SetErrorMessage("Unable to copy/create the following file :<br/>" + shareFolder + ";" + ex.Message, hfField);
                            break;

                        case 3:
                            SetErrorMessage("Your transmittal is saved with number:" + Log.ToString() + ", but unable to distribute.<br/>;" + ex.Message.Replace(Environment.NewLine, "<br/>"), hfField);
                            break;
                        default:
                            SetErrorMessage("Error;" + ex.Message.Replace(Environment.NewLine, "<br/>"), hfField);
                            break;
                    }
                }

                if (!isErr)
                {
                    string op = isDistribute ? "distributed" : "saved";
                    SetFlashMessage("Your Transmittal is " + op + " successfully, with the following information:<br/>Transmittal Log Number : " + Log.ToString(), hfField);
                }

                //   HandleRedirect(Log);

                TempFile.Clear(this);
            }
        }

        private void FillPopUp(string p)
        {
            IncomingTransmittal trns = CommonBusinessRules.GetIncomingTransmittal(CurrentUnitOfWork, p);
            if (trns != null)
            {
                lblPopNo.Text = string.Format("{0} ({1})", p, trns.Status);

                txtPopRemarks.Text = trns.Remarks;
                dtePopReceivedDate.Date = trns.ReceivedDate;
                txtPopSubject.Text = trns.Subject;
                cboPopFrom.Text = trns.From;
                cboPopInbox.Text = trns.InboxName;

                if (!hfField.Contains("Attn"))
                    hfField.Add("Attn", trns.Attn);
                else
                    hfField["Attn"] = trns.Attn;

                btePopAttn.Text = trns.AttnNames;

                if (!hfField.Contains("CC"))
                    hfField.Add("CC", trns.Cc);
                else
                    hfField["CC"] = trns.Cc;
                btePopCc.Text = trns.CcNames;
                //  lnkPopFile.Text = trns.OriginalFileName;
                //lblFile.Text = trns.OriginalFileName;
                btnChangeIncoming.Text = string.IsNullOrEmpty( trns.OriginalFileName)?"Click to upload.":trns.OriginalFileName;

                btnDistribute.Enabled = (trns.Status == IncomingTransmittal.STATUS_DRAFT);

                if (!hfField.Contains("uncLink"))
                    hfField.Add("uncLink", trns.UncLink);
                else
                    hfField["uncLink"] = trns.UncLink;


                TempFile.Clear(this);
            }
        }

        protected void clbPanelEdit_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            int opType = 0;
            int idValue = 1;
            string[] pars = e.Parameter.Split(';');
            switch (pars[opType])
            {
                case "load":
                    FillPopUp(pars[idValue]);
                    break;
                case "save":
                    SavePopUp(pars[idValue], false);
                    break;
                case "distribute":
                    DistributePop(pars[idValue]);
                    break;
            }
        }

        protected void SetErrorMessage(string message, DevExpress.Web.ASPxHiddenField.ASPxHiddenField hiddenField)
        {
            if (!hiddenField.Contains("error"))
                hiddenField.Add("error", message);
            else
                hiddenField["error"] = message;
        }
        protected void SetFlashMessage(string message, DevExpress.Web.ASPxHiddenField.ASPxHiddenField hiddenField)
        {
            if (!hiddenField.Contains("info"))
                hiddenField.Add("info", message);
            else
                hiddenField["info"] = message;
        }

        private void submitTransmittal(string p)
        {
            OutgoingTransmittal trns = CommonBusinessRules.GetOutgoingTransmittal(CurrentUnitOfWork, p);
            if (trns != null)
            {
                if (string.IsNullOrEmpty(trns.FaxFileLink) && TempFile.GetFileFromSession(this) == null)
                    SetErrorMessage("Error: please upload the document first", hfEdit);
                else
                {

                    saveEdit(p, false);
                    trns.Reload();
                    trns.Status = OutgoingTransmittal.WAIT;
                    trns.Save();
                    CurrentUnitOfWork.CommitChanges();
                    if (!hfEdit.Contains("error"))
                    {
                        SetFlashMessage("Your transmittal is successfully submitted.", hfEdit);
                    }

                }
            }
        }

        private void sendTransmittal(string id)
        {
            saveEdit(id, true);
        }

        private void saveEdit(string id, bool sendFax)
        {
            string subject = txtEditSubject.Text;
            string faxNo = txtEditFaxNo.Text;
            string author = cboAuthor.Text;
            string to = cboEditTo.Text;
            string remarks = txtEditRemarks.Text;
            string docTypeCode = cboEditDocType.Value == null ? "" : cboEditDocType.Value.ToString();
            string attn = txtEditAttn.Text;
            string log = id;

            TempFile file = TempFile.GetFileFromSession(this);
            string shareFolder;
            int step = 0;
            bool isErr = false;
            try
            {
                if (file == null)
                {
                    step = 1;
                    CommonBusinessRules.SaveOutgoing(CurrentUnitOfWork, log, subject, author, to, faxNo, docTypeCode, attn, remarks, CurrUserId);

                }
                else
                {
                    string ext = Path.GetExtension(file.File.FileName);

                    CommonBusinessRules.CheckExtention(CurrentUnitOfWork, ext);
                    string path = CommonBusinessRules.GetOutgoingShareFolderToWrite(CurrentUnitOfWork, log);
                    //   step = 2;
                    string newFileName = CommonBusinessRules.GetOutgoingTransmittalFileName(CurrentUnitOfWork, log, Path.GetExtension(file.File.FileName));
                    shareFolder = Path.Combine(path, newFileName);
                    file.File.SaveAs(shareFolder);
                    step = 1;
                    CommonBusinessRules.SaveOutgoing(CurrentUnitOfWork, log, subject, author, to, faxNo, docTypeCode, attn, remarks, CurrUserId, file.File.FileName , shareFolder);
                }
                if (sendFax)
                {
                    step = 3;
                    CommonBusinessRules.SendFax(CurrentUnitOfWork, log);
                }
            }
            catch (Exception ex)
            {
                isErr = true;
                switch (step)
                {
                    case 0:
                        SetErrorMessage("Error:Unable to write document;" + ex.Message, hfEdit);
                        break;
                    case 1:
                        SetErrorMessage("Error:unable to save transmittal;" + ex.Message, hfEdit);
                        break;
                    case 3:
                        SetErrorMessage(ex.Message, hfEdit);
                        break;
                    default:
                        SetErrorMessage("Error:" + ex.Message, hfEdit);
                        break;
                }
            }
            if (!isErr)
            {
                string op = sendFax ? "sent" : "saved";
                SetFlashMessage("Your Transmittal is " + op + " successfully, with the following information:<br/>Transmittal Log Number : " + id.ToString(), hfEdit);
            }
            TempFile.Clear(this);
        }

        private void loadEdit(string id)
        {
            OutgoingTransmittal trns = CommonBusinessRules.GetOutgoingTransmittal(CurrentUnitOfWork, id);
            if (trns != null)
            {
                //lblStatus.Text = trns.Status;
                lblLog.Text = String.Format("{0} ({1})", trns.ID.ToString(), trns.Status); ;
                lblRefNo.Text = trns.RefNo;
                txtEditAttn.Text = trns.Attn;
                txtEditFaxNo.Text = trns.FaxNo;
                txtEditRemarks.Text = trns.Remarks;
                txtEditSubject.Text = trns.Subject;
                cboEditDocType.Value = trns.DocTypeCode;
                cboAuthor.Text = trns.Author;
                cboEditTo.Text = trns.To;
                btnChangeOutgoing.Text = string.IsNullOrEmpty( trns.OriginalFileName)?"Click here to upload.":trns.OriginalFileName ;

                if (!hfEdit.Contains("uncLink"))
                    hfEdit.Add("uncLink", trns.UNC_LINK);
                else
                    hfEdit["uncLink"] = trns.UNC_LINK;

                btnSendFax.Enabled = (trns.Status == OutgoingTransmittal.WAIT);
                btnSubmit.Enabled = (trns.Status == OutgoingTransmittal.DRAFT);

                TempFile.Clear(this);
            }
        }

        protected void clbpnlPopEdit_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            string prm = e.Parameter;
            int opType = 0;
            int idValue = 1;
            string[] pars = e.Parameter.Split(';');
            switch (pars[opType])
            {
                case "load":
                    loadEdit(pars[idValue]);
                    break;
                case "save":
                    saveEdit(pars[idValue], false);
                    break;
                case "send":
                    sendTransmittal(pars[idValue]);
                    break;
                case "submit":
                    submitTransmittal(pars[idValue]);
                    break;
            }
        }

        protected void upcPopDoc_FileUploadComplete1(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
        {
            if (e.UploadedFile != null)
            {
               // TempFile.StoreTempFile(this, e.UploadedFile);
                TempFile.StoreToTempFolder(this, e.UploadedFile);
                e.CallbackData = e.UploadedFile.FileName;
                e.IsValid = true;
            }
        }

        protected void upcDocument_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
        {
            if (e.UploadedFile != null)
            {
               //TempFile.StoreTempFile(this, e.UploadedFile);
                TempFile.StoreToTempFolder(this, e.UploadedFile);
                e.CallbackData = Path.GetFileName(e.UploadedFile.FileName);
                e.IsValid = true;
            }
        }

        protected void clbCancel_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
        {
            OutgoingTransmittal trns = CommonBusinessRules.GetOutgoingTransmittal(CurrentUnitOfWork, e.Parameter);
            if (trns != null)
            {
                TempFile.Clear(this);
                e.Result = trns.OriginalFileName;
            }
        }

        protected void clbCancelIncoming_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
        {
            IncomingTransmittal trns = CommonBusinessRules.GetIncomingTransmittal(CurrentUnitOfWork, e.Parameter);
            if (trns != null)
            {
                e.Result = trns.OriginalFileName;
                TempFile.Clear(this);
            }
        }

        protected void grdEmployee_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            //string param = e.Parameters;
            //if (param == "bind")
            //{
            //    Session[SESSION_KEY_EMPLOYEE] = CommonBusinessRules.GetEmployeetable(ConfigurationManager.AppSettings["LDAP_URL"]);
            //    grdEmployee.DataSource = (DataTable)Session[SESSION_KEY_EMPLOYEE];
            //    grdEmployee.DataBind();
            //}
            string[] prms = e.Parameters.Split(';');
            string param = prms[0];
            List<string> ids = new List<string>();
            if (param == "bind")
            {
                grdEmployee.Selection.UnselectAll();
                if (prms[1] == "attn")
                {
                    string attn = btePopAttn.Text;
                    ids.AddRange(attn.Split(';'));
                }
                else
                {
                    string cc = btePopCc.Text;
                    ids.AddRange(cc.Split(';'));
                }
                foreach (string id in ids)
                {
                    if (!string.IsNullOrEmpty(id))
                        grdEmployee.Selection.SelectRowByKey(id);
                }

                //Session[SESSION_KEY_EMPLOYEE] = CommonBusinessRules.GetEmployeetable(ConfigurationManager.AppSettings["LDAP_URL"]);
                //grdEmployee.DataSource = (DataTable)Session[SESSION_KEY_EMPLOYEE];
                grdEmployee.DataBind();
            }
        }

        protected void grdOutstandingIncoming_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            grdOutstandingIncoming.DataBind();
        }

        protected void grdOutstandingTransmittal_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            grdOutstandingTransmittal.DataBind();
        }

        protected void hfField_CustomCallback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            string[] prms = e.Parameter.Split(';');
            string value = "";
            if (prms.Length == 1)
            {
                TempFile tf = TempFile.GetFileFromSession(this);
                if (!string.IsNullOrEmpty(tf.TempFileLoc))
                {
                    value = tf.TempFile_UNC_Link;
                }
            }
            else
            {
                IncomingTransmittal trns = CommonBusinessRules.GetIncomingTransmittal(CurrentUnitOfWork, prms[1]);
                if (trns != null)
                {
                    value = trns.GetUNC_FileLink();
                }
            }

            if (!hfField.Contains("uncLink"))
                hfField.Add("uncLink", value);
            else
                hfField["uncLink"] = value;
        }

        protected void hfEdit_CustomCallback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            string[] prms = e.Parameter.Split(';');
            string value = "";
            if (prms.Length == 1)
            {
                TempFile tf = TempFile.GetFileFromSession(this);
                if (tf != null)
                {
                    if (!string.IsNullOrEmpty(tf.TempFileLoc))
                    {
                        value = tf.TempFile_UNC_Link;
                    }
                }
            }
            else
            {
                OutgoingTransmittal trns = CommonBusinessRules.GetOutgoingTransmittal(CurrentUnitOfWork, prms[1]);
                if (trns != null)
                {
                    value = trns.GetUNC_FileLink();
                }
            }

            if (!hfEdit.Contains("uncLink"))
                hfEdit.Add("uncLink", value);
            else
                hfEdit["uncLink"] = value;
        }
    }
}